package com.xoms.pad.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xoms.pad.aspect.datasource.DataSourceSwitcher;
import com.xoms.pad.controller.OrderProJsonBean;
import com.xoms.pad.controller.res.bean.ROrderListBean;
import com.xoms.pad.controller.res.bean.ROrderRoomDimensionBean;
import com.xoms.pad.controller.res.bean.RProOrderBean;
import com.xoms.pad.controller.res.bean.RProductOrderBean;
import com.xoms.pad.model.AccountBean;
import com.xoms.pad.model.CounterBean;
import com.xoms.pad.model.OrderBean;
import com.xoms.pad.model.OrderRoomDimensionBean;
import com.xoms.pad.model.ProOrderBean;
import com.xoms.pad.model.ProStockBean;
import com.xoms.pad.model.ProductBean;
import com.xoms.pad.persist.dao.CounterDao;
import com.xoms.pad.persist.dao.OrderDao;
import com.xoms.pad.persist.dao.ProOrderDao;
import com.xoms.pad.persist.dao.ProStockDao;
import com.xoms.pad.persist.dao.ProductDao;
import com.xoms.pad.persist.dao.RoomDao;
import com.xoms.pad.service.OrderService;
import com.xoms.pad.service.exception.ServiceException;
import com.xoms.pad.service.res.PageResult;
import com.xoms.util.AppTextUtil;
import com.xoms.util.NumUtil;
import com.xoms.util.StringUtil;

@Service
public class OrderServiceImpl implements OrderService {
	
	
	Logger logger = Logger.getLogger(this.getClass());

	@Autowired
	OrderDao orderImpl;
	
	@Autowired
	ProductDao productImpl;
	
	@Autowired
	ProOrderDao proOrderImpl;
	
	@Autowired
	ProStockDao proStockImpl;
	

	@Autowired
	CounterDao counterImpl;
	
	@Autowired
	RoomDao roomImpl;


	@Override
	public RProductOrderBean getAddOrder(AccountBean account, List<OrderProJsonBean> pros, double actualMoeny,
			int payType,  String roomId,int isHand, String handRoomId, int isAuth, double authMoney, String authAccountId,
			String deviceMac) {
		boolean flag = false;
		if (pros == null || pros.size() == 0) {
			throw new ServiceException("object_is_not_exist", "商品");
		}

		// 切换至影院数据源
		DataSourceSwitcher.setDataSourceType(DataSourceSwitcher.DATA_SOURCE_XOMS);
		// 当前账户所在的柜台
		List<CounterBean> storeHouses = counterImpl.selectCounterByAccId(account.getAccid());
		
		if(storeHouses == null || storeHouses.size()<=0 ){
			throw new ServiceException("object_is_not_exist", "当前账户关联柜台");
		}
		// 柜台id
		String sid = storeHouses.get(0).getSid();

		List<String> pids = new ArrayList<>();
		pros.forEach(pro -> {
			pids.add(pro.getPid());
		});

		Map<String, OrderProJsonBean> prosMap = pros.stream()
				.collect(Collectors.toMap(OrderProJsonBean::getPid, p -> p));

		// 根据pids查询
		List<ProductBean> lists = productImpl.selectListByPids(pids);
		if (lists == null || lists.size() == 0 || pids.size() != lists.size()) {
			throw new ServiceException("object_is_not_exist", "商品");
		}

		// 总价
		double money = 0;
		for (ProductBean pro : lists) {
			OrderProJsonBean orderPro = prosMap.get(pro.getPid());
			money += Math.abs(NumUtil.toDouble(pro.getPrice(), 0)) * Math.abs(NumUtil.toDouble(orderPro.getNum(), 0));
		}



		// 订单信息
		String oid = AppTextUtil.getPrimaryKey();
		logger.info("oid:" + oid);
		
		OrderBean order = new OrderBean();
		order.setOid(oid);
		order.setOrderNo(AppTextUtil.getRandomNo());
		order.setOrderType(4);
		order.setTargetId("");
		order.setCreateTime(new Timestamp(System.currentTimeMillis()));
		order.setPayType(payType);
		order.setSendStatus(0);// 未配送
		order.setSubject("产品下单");

		// 实际金额，优惠的价格
		double getMoney = money;
		// 是否授权优惠 0未授权，1授权
		if (isAuth == 1) {
			getMoney -= Math.abs(authMoney);
			order.setIsAuth(1);
			order.setAuthAccountId(authAccountId);
			order.setAuthTime(new Timestamp(System.currentTimeMillis()));
			order.setAuthMoney(Math.abs(authMoney));
		} else {
			order.setIsAuth(0);
		}
		order.setRoomId(roomId);		
		// 是否挂帐 0不挂，1挂
//		if (isHand == 1) {
//			if (StringUtil.isEmpty(roomId)) {
//				throw new ServiceException("param_input_is_not_empty", "影厅");
//			}
//			order.setIsHand(1);
//			order.setHandRoomId(handRoomId);
//		} else {
//			order.setIsHand(0);
//			order.setHandRoomId("");
//		}
		order.setIsHand(0);
		order.setHandRoomId("");
		order.setMoney(money);
		order.setGetMoney(getMoney);

		// 是否支付状态
		int isPay = 0;
		
		// 支付方式：1会员卡支付,2现金,3银联,4支付宝,5微信,6信用卡,7签单
		//  4 5 为未支付其它为已经支付
//		if (payType == 1 || payType == 2 || payType == 3 || payType == 6 || payType == 7) {
//			order.setPayTime(new Timestamp(System.currentTimeMillis()));			
//			isPay = 1;
//		}else if (payType == 4 || payType == 5){
//			order.setPayTime(new Timestamp(System.currentTimeMillis()));
//			isPay = 0;
//		}
		order.setActionId(account.getAccid());
		order.setDeviceMac(deviceMac);
		order.setStatus(isPay);
		//订单表
		System.out.println(order.toString());
		flag = orderImpl.insert(order) > 0;
		if (!flag) {
			throw new ServiceException("database_insert_fail", "订单");
		}

		// 订单商品明细
		List<ProOrderBean> proOrderList = new ArrayList<>();
		List<ProStockBean> proStockList = new ArrayList<ProStockBean>();
		for (ProductBean pro : lists) {
			ProOrderBean proOrder = new ProOrderBean();
			proOrder.setOid(oid);
			proOrder.setProductId(pro.getPid());
			proOrder.setOrderCode("");
			proOrder.setPrice(pro.getPrice());
			OrderProJsonBean orderPro = prosMap.get(pro.getPid());
			proOrder.setNumber(Math.abs(orderPro.getNum()));
			proOrder.setTotalPrice(Math.abs(orderPro.getNum()) * pro.getPrice());
			proOrder.setCreateTime(new Timestamp(System.currentTimeMillis()));
			//proOrder.setCreateTime(System.currentTimeMillis());
			proOrder.setStatus(isPay);
			proOrder.setAccountId(account.getAccid());
			proOrder.setCounterId(sid);
			proOrderList.add(proOrder);
			

			ProStockBean stock = new ProStockBean();
			stock.setStoreHouseId(sid);
			stock.setProductId(pro.getPid());
			stock.setStore(-Math.abs(orderPro.getNum()));
			proStockList.add(stock);
		}
		//订单商品明细
		flag = proOrderImpl.insertBatch(proOrderList) > 0;
		if (!flag) {
			throw new ServiceException("database_insert_fail", "订单商品");
		}
		//修改库存
		flag = proStockImpl.updateBatch(proStockList) > 0;
		if (!flag) {
			throw new ServiceException("database_update_fail", "商品库存");
		}
		RProductOrderBean  rProductOrderBean = new RProductOrderBean();
		rProductOrderBean.setOid(oid);
		rProductOrderBean.setOrderNo(order.getOrderNo());
		return rProductOrderBean;
	}
	
	
	@Override
	public PageResult<ROrderListBean> orderList(AccountBean account,String oid,int sendStatus,int status,int orderType,int page, int pageSize) {
		PageResult<ROrderListBean> result = new PageResult<>();
		// 切换至影院数据源
		DataSourceSwitcher.setDataSourceType(DataSourceSwitcher.DATA_SOURCE_XOMS);

		int count = orderImpl.selectCount();
		List<OrderBean> list = orderImpl.selectList(account.getAccid(),oid, sendStatus, status,orderType,page, pageSize);

		List<ROrderListBean> resList = new ArrayList<>();
		if (list != null && list.size() > 0) {
			for (OrderBean o : list) {
				ROrderListBean rb = parseOrder(o);
				resList.add(rb);
			}
		}
		result.setCount(count);
		result.setData(resList);
		return result;
	}

	private ROrderListBean parseOrder(OrderBean o) {
		ROrderListBean resBean = new ROrderListBean();
		resBean.setOid(o.getOid());
		resBean.setHandRoomId(o.getHandRoomName());
		resBean.setRoomName(o.getRoomName());
		resBean.setSendStatus(o.getSendStatus());
		resBean.setIsHand(NumUtil.toInt(o.getIsHand(), 0));
		resBean.setRoomId(o.getRoomId());
		resBean.setOrderNo(o.getOrderNo());
		resBean.setOrderType(o.getOrderType());
		resBean.setTargetId(o.getTargetId());
		resBean.setMoney(o.getMoney());
		resBean.setGetMoney(o.getGetMoney());
		resBean.setIsAuth(NumUtil.toInt(o.getIsAuth(), 0));
		resBean.setAuthAccountId(o.getAuthAccountId());
		resBean.setAuthAccountName("");
		resBean.setAuthTime(o.getAuthTime() != null ? o.getAuthTime().getTime() / 1000 : 0);
		resBean.setAuthMoney(o.getAuthMoney());
		resBean.setCreateTime(o.getCreateTime() != null ? o.getCreateTime().getTime() / 1000 : 0);
		resBean.setStatus(NumUtil.toInt(o.getStatus(), 0));
		resBean.setPayType(NumUtil.toInt(o.getPayType(), 0));
		resBean.setPayTime(o.getPayTime() != null ? o.getPayTime().getTime() / 1000 : 0);
		resBean.setActionId(o.getActionId());
		resBean.setActionName("");
		resBean.setDeviceMac(o.getDeviceMac());
		resBean.setCompleteTime(o.getCompleteTime() != null ? o.getCompleteTime().getTime() / 1000 : 0);
		
		//获取订单影厅维度
		DataSourceSwitcher.setDataSourceType(DataSourceSwitcher.DATA_SOURCE_XOMS);//获取数据源
		String roomId = o.getRoomId();
		List<OrderRoomDimensionBean> OrdRoomDimList = roomImpl.selectOrderRoomDimension(roomId);
		List<ROrderRoomDimensionBean> roomDim = new ArrayList<>();
		for(OrderRoomDimensionBean ordRoomDim: OrdRoomDimList){
			ROrderRoomDimensionBean rOrdRoomDim = new ROrderRoomDimensionBean();
			rOrdRoomDim.setDid0(ordRoomDim.getDid0());
			rOrdRoomDim.setName0(ordRoomDim.getName0());
			rOrdRoomDim.setDid(ordRoomDim.getDid());
			rOrdRoomDim.setName(ordRoomDim.getName());;
			roomDim.add(rOrdRoomDim);
		}
		resBean.setDimension(roomDim);
		
		//获取订单商品信息
		DataSourceSwitcher.setDataSourceType(DataSourceSwitcher.DATA_SOURCE_XOMS);//获取数据源
		String oid = o.getOid();
		List<ProOrderBean> orderProList = orderImpl.selectOrderProList(oid);
		List<RProOrderBean> rProOrder = new ArrayList<>();
		for(ProOrderBean orderPro: orderProList){
			RProOrderBean rProOrderBean = new RProOrderBean();
			rProOrderBean.setAccountId(orderPro.getAccountId());
			rProOrderBean.setCounterId(orderPro.getAccountId());
			rProOrderBean.setCreateTime(orderPro.getCreateTime().getTime());
			rProOrderBean.setFromCounterId(orderPro.getFromCounterId());
			rProOrderBean.setOid(orderPro.getOid());
			rProOrderBean.setStatus(orderPro.getStatus());
			rProOrderBean.setTotalPrice(orderPro.getTotalPrice());
			rProOrderBean.setPrice(orderPro.getPrice());
			rProOrderBean.setNumber(orderPro.getNumber());
			rProOrderBean.setProductId(orderPro.getProductId());
			rProOrderBean.setProductName(orderPro.getProductName());
			rProOrder.add(rProOrderBean);
		}
		resBean.setOrderPro(rProOrder);
		
		return resBean;
	}

	//修改订单
	@Override
	public Boolean modifyOrder(AccountBean account, String oid, String payType, String isHand,
			String roomId, String handRoomId, String payStatus) {
		boolean flag = false;
		if (oid == null) {
			throw new ServiceException("object_is_not_exist", "订单号");
		}
		if (payType == null) {
			throw new ServiceException("object_is_not_exist", "支付方式");
		}
		if (roomId == null) {
			throw new ServiceException("object_is_not_exist", "影厅ID");
		}
		
		if(Integer.valueOf(payType) == 7){
			if (isHand == null) {
				throw new ServiceException("object_is_not_exist", "是否挂账");
			}
			if (handRoomId == null) {
				throw new ServiceException("object_is_not_exist", "挂账影厅ID");
			}
		}
		// 切换至影院数据源
		DataSourceSwitcher.setDataSourceType(DataSourceSwitcher.DATA_SOURCE_XOMS);
		int  ret = orderImpl.selectModifyOrder(oid, payType, isHand, roomId,handRoomId,payStatus);
		if(ret>=0){
			flag = true;
		}
		return flag;
	}

}
